import api from "../../utils/apis.js";
import message from "../../utils/message.js";
import util from "../../utils/util.js";
let app = getApp();

Page({
  data: {
    isSaveIma: false,
    isShow: false,
    isQcodeShow: false,
    isKeFuShow: false,
    isPhoneShow: false,
    iWalletShow: false,
    inviteNum: 0,
    countNum: 60,

    phoneValue: null,
    verifyCode: null,
    walletAddress: null,
    listLength: 1,
    size: 20,
    pageNum: 0,
    loadMoreTitle: '点击加载更多',
    userId: null,
    userNickName: '',
    defaultNickName: '***',
    loading: false,
    imgUrl: null,
    phone: "",
    wallet: "",
    inviteData: [],
    imgalist: ["http://www.valuechain.group/template/userEr.png"],
    localHeadUrl: '/images/assets/logo.jpg',
    ///////授权
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse("button.open-type.getUserInfo"),
    touchStart: null,
    touchEnd: null
  },
  onReady: function() {
    this.animation = wx.createAnimation()
  },

  ///////////获取用户的个人信息//////////
  getbaseInfo() {
    let self = this;
    let token = wx.getStorageSync("authorization");

    wx.showLoading({
      title: "加载中"
    });
    wx.request({
      url: api.getBaseInfoApi,
      method: "GET",
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        if (res.statusCode == 200) {
          let cashWallet = res.data.cashWallet;
          if (cashWallet) {
            let len = cashWallet.length;
            let a = cashWallet.slice(0, 8);
            let b = cashWallet.slice(len - 8, len);
            let wallet_1 = a + "..." + b;
            self.setData({
              wallet: wallet_1
            });
          }
          if (res.data.mobile && res.data.mobile != 'null') {
            self.setData({
              phone: res.data.mobile,
              isPhoneShow: false
            });
          } else {
            self.setData({
              isPhoneShow: true
            });
          }
          if (res.data.userId) {
            self.setData({
              userId: res.data.userId
            });
          }

          if (res.data.nickname) {
            self.setData({
              userNickName: res.data.nickname
            })
          }
        } else {
          if (res.data.title == 'Unauthorized') {
            wx.redirectTo({
              url: '/pages/login/login'
            })
            return
          } else {
            message.showInfo(
              res.data.message ? res.data.message : "网络连接异常"
            );
          }
        }
      }
    });
  },
  //////////获取用户的邀请信息//////////
  /////////分页///////////
  clickMore() {
    let self = this;

    self.setData({
      loading: true
    });
    self.data.pageNum++;
    self.invition(self.data.pageNum);
  },
  /////////邀请明细///////
  invition(page) {
    let self = this;

    let token = wx.getStorageSync("authorization");
    wx.showLoading({
      title: "加载中"
    });
    wx.request({
      url: api.inviteInfo + "?size=" + this.data.size + "&page=" + page,
      method: "GET",
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        if (res.statusCode == 200) {

          let total = res["header"]["X-Total-Count"];

          if (res.data.length == 0) {
            self.setData({
              loadMoreTitle: '无更多数据'
            })
          }

          if (res.data) {
            let temp = [];
            self.data.inviteData.forEach(element => {
              temp.push(element);
            });

            res.data.forEach(element => {
              if (element.inviteDate) {
                element.inviteDate = element.inviteDate.substring(0, 10)
              }

              if (element.nickName) {

              } else {
                element.nickName = ''
              }

              temp.push(element);
            });

            self.setData({
              listLength: total,
              loading: false,
              inviteNum: total,
              inviteData: temp
            });
          } else {
            self.setData({
              listLength: total,
              loading: false,
              inviteNum: total
            });
          }
        } else {
          util.errHandler(res)
        }
      }
    });
  },

  ///////////////////绑定事件//////////
  /////////绑定手机号/////
  //发送验证码
  sendSmsAction: function() {
    let self = this;
    if (!self.data.phoneValue) {
      wx.showToast({
        title: "手机号不能为空",
        icon: "",
        image: "/images/logo/warning.png",
        duration: 2000
      });
      return;
    }

    if (self.data.phoneValue.length != 11) {
      wx.showToast({
        title: "手机号不正确",
        icon: "",
        image: "/images/logo/warning.png",
        duration: 2000
      });
      return;
    }

    let param = {
      mobile: self.data.phoneValue
    };

    wx.showLoading({
      title: "加载中"
    });
    wx.request({
      url: api.sendSmsCode,
      method: "POST",
      data: param,
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        wx.hideLoading();
        message.showSuccess("验证码已发送");
        if (res.statusCode == "200") {
          let temp = setInterval(() => {
            if (self.data.countNum == 0) {
              self.setData({
                countNum: 60
              });

              self.setData({
                countText: "发送验证码"
              });

              if (
                self.data.intervalNum != null &&
                self.data.intervalNum != undefined
              ) {
                clearInterval(self.data.intervalNum);
              }
            } else {
              let num2 = self.data.countNum;
              num2 -= 1;
              self.setData({
                countNum: num2
              });
            }
          }, 1000);

          self.setData({
            intervalNum: temp
          });
        } else {
          message.showInfo(
            res.data.message ? res.data.message : "网络连接异常"
          );
        }
      }
    });
  },
  bindPhoneSure() {
    let self = this;

    let token = wx.getStorageSync("authorization");

    wx.showLoading({
      title: "加载中"
    });
    wx.request({
      url: api.bindPhoneApi +
        "?mobile=" +
        self.data.phoneValue +
        "&smsCode=" +
        self.data.verifyCode,
      method: "POST",
      // data: param,
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        if (res.statusCode == 200) {
          wx.showToast({
            title: "已绑定手机"
          });
          self.setData({
            // phone: self.data.phoneValue,
            isPhoneShow: false
          });

          let token = res.data.id_token;
          try {
            wx.setStorageSync("authorization", token);
          } catch (e) {
            console.log(e);
          }

          self.getbaseInfo();
        } else {
          if (res.data.title == 'Unauthorized') {
            wx.redirectTo({
              url: '/pages/login/login'
            })
            return
          } else {
            message.showInfo(
              res.data.message ? res.data.message : "网络连接异常"
            );
          }
        }
      }
    });
  },
  ///////绑定钱包地址/////
  bindWalletFun() {
    let self = this;
    let token = wx.getStorageSync("authorization");
    wx.showLoading({
      title: "加载中"
    });
    wx.request({
      url: api.bindWalletApi + "?wallet=" + self.data.walletAddress,
      method: "POST",
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        if (res.statusCode == 200) {
          let len = self.data.walletAddress.length;
          let a = self.data.walletAddress.slice(0, 8);
          let b = self.data.walletAddress.slice(len - 8, len);
          let wallet_1 = a + "..." + b;
          self.setData({
            wallet: wallet_1,
            iWalletShow: false,
          })

        } else {
          util.errHandler(res)
        }
      }
    });
  },
  ///////////////////图片的保存//////////
  /////////生成二维码/////
  getqcode() {
    let self = this;
    self.setData({
      isQcodeShow: true
    });

    let token = wx.getStorageSync("authorization");
    wx.showLoading({
      title: "加载中"
    });

    wx.request({
      url: api.getQcodeApi + "?scene=" + self.data.userId + "&width=" + 320,
      method: "GET",
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        if (res.statusCode == 200) {
          var array = wx.base64ToArrayBuffer(res.data);
          var base64 = wx.arrayBufferToBase64(array);
          self.setData({
            imgUrl: "data:image/png;base64," + base64
          });
          wx.hideLoading();
        } else {
          util.errHandler(res)
        }
      }
    });
  },
  ////////展示二维码图片///
  baocun() {
    let self = this;
    this.setData({
      isShow: false,
      isQcodeShow: true
    });
    self.getqcode();
  },
  ////////保存二维码图片///
  sure() {
    let self = this;
    var aa = wx.getFileSystemManager();
    aa.writeFile({
      filePath: wx.env.USER_DATA_PATH + "/test.png",
      data: self.data.imgUrl.slice(22),
      encoding: "base64",
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: wx.env.USER_DATA_PATH + "/test.png",
          success: function(res) {
            wx.showToast({
              title: "已成功保存到相册"
            });
          },
          fail: function(err) {
            wx.showToast({
              title: "请前往小程序设置更改授权项",
              icon: 'none'
            });
          }
        });
      },
      fail: err => {
        console.log(err);
      }
    });
  },
  ///////客服图片/////
  /////长按保存//////
  touchStart: function(e) {
    let self = this;
    self.setData({
      touchStart: e.timeStamp
    });
  },
  touchEnd: function(e) {
    let self = this;
    self.setData({
      touchEnd: e.timeStamp
    });
  },
  saveImg: function() {
    let self = this;
    self.setData({
      isSaveIma: true
    });
    self.animation.translateY(-60).step();
    self.setData({
      animation: self.animation.export()
    });
  },

  previewImage: function(e) {
    wx.previewImage({
      current: this.data.imgalist, // 当前显示图片的http链接
      urls: this.data.imgalist // 需要预览的图片http链接列表
    });
  },
  //////点击保存////
  save() {
    let self = this;
    var imgSrc = "http://www.valuechain.group/template/userEr.png";
    wx.downloadFile({
      url: imgSrc,
      success: function(res) {
        console.log(res);
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(data) {
            wx.showToast({
              title: "保存成功",
              icon: "success",
              duration: 2000
            });
            self.setData({
              isKeFuShow: false
            });
          },
          fail: function(err) {
            console.log(err);
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("当初用户拒绝，再次发起授权");
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata);
                  if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                    console.log(
                      "获取权限成功，给出再次点击图片保存到相册的提示。"
                    );
                  } else {
                    console.log(
                      "获取权限失败，给出不给权限就无法正常使用的提示"
                    );
                  }
                }
              });
            }
          },
          complete(res) {
            console.log(res);
          }
        });
      }
    });
  },
  ///////////////////////////////////////////////页面逻辑交互///////////////////
  invite() {
    this.setData({
      isShow: true
    });
  },
  celSaveImag() {
    this.setData({
      isSaveIma: false
    });
  },
  celInvite() {
    this.setData({
      isShow: false
    });
    console.log(this.data.isShow);
  },
  cancelStyle() {
    this.setData({
      isQcodeShow: false
    });
  },
  //点击查看客服
  kefu() {
    console.log("ni");
    this.setData({
      isKeFuShow: true
    });
  },
  cancelkefu() {
    this.setData({
      isKeFuShow: false
    });
  },
  bindPhone() {
    let self = this;
    self.setData({
      isPhoneShow: true
    });


    if (this.data.phone) {
      this.setData({
        phoneValue: this.data.phone
      })
    }
  },
  bindWallet() {
    this.setData({
      iWalletShow: true
    });
  },
  cancelPhone() {
    this.setData({
      isPhoneShow: false
    });
  },
  cancelWallet() {},
  cancelPhone() {
    this.setData({
      isPhoneShow: false
    });
  },
  cancelWallet() {
    this.setData({
      iWalletShow: false
    });
  },

  //监听手机号码的输入
  bindKeyInput: function(e) {
    this.setData({
      phoneValue: e.detail.value
    });
  },
  //监听验证码的输入
  bindCodeInput: function(e) {
    this.setData({
      verifyCode: e.detail.value
    });
  },
  //绑定钱包地址
  bindKeyWallet: function(e) {
    this.setData({
      walletAddress: e.detail.value
    });
  },

  /////////////////////////////////////////////////////////////////////////////
  onLoad: function(options) {
    let self = this;
  },

  onShow() {
    let self = this;

    self.setData({
      inviteData: []
    })
    self.invition(0, 6);
    self.getbaseInfo();
  },

  onShareAppMessage: function(res) {
    if (res.from === "button") {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: this.data.userNickName + '邀你一起加入星空矿机',
      path: "/pages/index/index?inviteUserId=" + this.data.userId,
      imageUrl: '/images/assets/shareImage.png'
    };
  }
});